import { defineStore } from "pinia";
import {
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import type { adminType } from "../types";
import { type AdminResult, login, getAdminInfo } from "@/api/admin";
import { setToken, setUserInfo, removeToken, userKey } from "@/utils/auth";
import { useMultiTagsStoreHook } from "./multiTags";

export const useAdminStore = defineStore({
  id: "admin",
  state: (): adminType => ({
    adminId: storageLocal().getItem(userKey)?.adminId ?? "",
    adminCode: storageLocal().getItem(userKey)?.adminCode ?? "",
    adminName: storageLocal().getItem(userKey)?.adminName ?? ""
  }),

  actions: {
    SET_ADMIN_ID(adminId: number) {
      this.adminId = adminId;
    },
    SET_ADMIN_CODE(adminCode: string) {
      this.adminCode = adminCode;
    },
    SET_ADMIN_NAME(adminName: string) {
      this.adminName = adminName;
    },

    /** 登录 */
    async loginByAdminCodeByPass(data) {
      console.log("1 loginByAdminCodeByPass");
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          if (res.code === 200) {
            console.log("2 data");
            console.log(res);
            console.log(res.token);
            setToken({
              token: res.data.token
            });
            resolve(res.code);
          } else {
            resolve(res.message);
          }
        });
      });
    },

    /** 获取用户信息 */
    async getAdminInfoByCode(data?: object) {
      return new Promise<AdminResult>((resolve, reject) => {
        getAdminInfo(data).then(res => {
          if (res.code === 200) {
            setUserInfo({
              adminId: res.data.adminId,
              adminCode: res.data.adminCode,
              adminName: res.data.adminName
            });
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    /** 退出登录 */
    logOut() {
      this.adminName = "";
      removeToken();
      resetRouter();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      router.push("/login");
    }
  }
});

export function useAdminStoreHook() {
  return useAdminStore(store);
}
